﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Training.Dia1.Data.Entities;

namespace Training.Dia1.Data.Managers
{
    public class ProductManager
    {
        public static IList<Product> GetList(string filter)
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                return ctx.Products.Where(u => u.Name.Contains(filter)).Include(t => t.MeasureUnit).ToList();
            }
        }

        public static Product Create(Product product)
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                product.MeasureUnit = ctx.MeasureUnits.Find(product.MeasureUnitId);
                Product productDB = ctx.Products.Add(product);

                ctx.SaveChanges();
                return productDB;
            }
        }
        public static Product Update(Product product)
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                product.MeasureUnit = ctx.MeasureUnits.Find(product.MeasureUnitId);
                ctx.Entry(product).State = EntityState.Modified;

                ctx.SaveChanges();
                return product;
            }
        }
        public static Product GetById(Guid id)
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                Product productDB = ctx.Products.Find(id);
                if (productDB == null)
                {
                    throw new Exception("Product not found in data base");
                }
                return productDB;
            }
        }
        public static void Delete(Guid id)
        {
            using (TrainingDia1DbContext ctx = new TrainingDia1DbContext())
            {
                Product productDB = ctx.Products.Find(id);
                if (productDB == null)
                {
                    throw new Exception("Product not found in data base");
                }
                ctx.Products.Remove(productDB);
                ctx.SaveChanges();

            }
        }
    }
}
